var WatchListSettingMenu = function(container, config, callbacks){
    this.container = container,qslan=QS_Lang.watchlist;
    this.HTML = '<div class="rtq-wl-settingpn"></div>';
    this.el = null;
    this.typeDDL = null;
    this.groupDDL = null;
    this.vwMenu = null;//watchlist menu, portfolio menu, type drop-down list,group drop-down list, view menu
    this._vwDisabled = false;
    this.moreDataWL = [];
    this.moreDataView = [];
    this.isShowHideChecked = true;
    this.config = {
        className: 'rtq-setting-plugin-black',
        width: 167,
        showLockCheckable: false,
        description: '<span>'+qslan["defaultlabel"]+'</span>',
        showTabRadio: true,
        tabRadioTxt: qslan["defaultautolabel"],
        defViewList: [],
        layoutList: [],
        displayLayout: 'list',
        groupByList: [],
        groupBy: '',
        isShowSummary: false,
        viewCount:6,
        isCheckAutoAddSymbol: true,
        isCheckLock: false,
        isSelectAuto: true,
        isSelectTabName: false,
        isShowHideChecked: true,
        currentViewName: qslan["intraday"]
    };
    $.extend(this.config, config);
    this.callbacks = {
        onTitleChange: function(title){},
        onLock: function(isLock){},
        onShowHideCheck: function(selected, flag){},
        onClickStartUp: function(){},
        onShowSummaryClick: function(isSelected){},
        onImportClick: function(productCode){},
        onChangeDisplayDDL: function(displayType){},
        onChangeGroupDDL: function(groupBy){},
        onViewAction: function(action, viewId){} //action: /select/add/edit/delete
    };
    $.extend(this.callbacks, callbacks);
    
    this.viewData = [{
        txt: qslan["newview"],
        val: 'cv_add',
        o: 'new'
    }, {
        type: "separator"
    }];
    
    this.init();
};
WatchListSettingMenu.prototype = {
    init: function(){
        var self = this,qslan=QS_Lang.watchlist;
        this.el = $(this.HTML).appendTo(this.container);
        this.settingGroupList = [{
            name: qslan["displaylabel"],
            id: 1
        }, {
            name: qslan["windowlabel"],
            id: 2
        }];
        var displayHTML = '<ul class="rtq-wl-sp-ul clearfix">' +
        '<li class="rtq-wl-sp-li rtq-wl-sp-title" ><h5>'+qslan["wl"]+'/'+qslan["pl"]+'</h5></li>' +
        '<li class="rtq-wl-sp-li" ><a class="open-start-up" href="#" style="display:block;border:1px solid #A5A5A5;background:#363636;color:#ECECEC;font-size:93%;padding:2px 3px;">'+qslan["select"]+'</a></li>' +
        '<li class="rtq-wl-sp-li l5" style="display:none;"><button>Import Office Watchlist</button></li>' +
        '<li class="rtq-wl-sp-li l6" style="display:none;"><button>Import Direct Watchlist</button></li>' +
        '<li class="rtq-wl-sp-li rtq-wl-sp-title"><h5>'+qslan["typelabel"]+'</h5></li>' +
        '<li class="rtq-wl-sp-li l2"><div class="rtq-wl-sp-tl"></div></li>' +
        '<li class="rtq-wl-sp-li rtq-wl-sp-title"><h5>'+qslan["grouplabel"]+'</h5></li>' +
        '<li class="rtq-wl-sp-li l3"><div class="rtq-wl-sp-gl"></div></li>' +
        '<li class="rtq-wl-sp-li rtq-wl-sp-title"><h5>'+qslan["viewlabel"]+'</h5></li>' +
        '<li class="rtq-wl-sp-li l4"><div class="rtq-wl-sp-vl rtq-ddl rtq-ddl-black"><div class="rtq-ddl-ipt rtq-vl" readonly="readonly" style="width:135px;" val=""></div></div></li>' +
        '<li class="rtq-wl-sp-li l7"><div class="summary-show-or-hide"></div></li>' +
        '</ul>';
        var settingGroup = new Util.GroupBox(this.el, this.settingGroupList, {
            width: 177,
            groupBoxHeight: 207,
            autoHeight: false
        });
        var gb1 = settingGroup.getGroup(1).bd, gb2 = settingGroup.getGroup(2).bd;
        gb1.append(displayHTML);
        this.settingPanelPluginForWindow = new SettingPlugin(gb2, this.config, {
            onChangeTitle: function(title, isAdd, isAuto, isShowTabName){
                if (isAuto) {
                    self.callbacks.onTitleChange(qslan["wl"]);
                }else {
                    if (isShowTabName) {
                        self.callbacks.onTitleChange('');
                    }else {
                        self.callbacks.onTitleChange(title);
                    }
                }
            },
            onCheckLock: function(lock){
                self.callbacks.onLock(lock);
            },
            onShowHide: function(selected, flag){
                self.callbacks.onShowHideCheck(selected, flag);
            }
        });
        //create default view data
        //var defViewData = this.wtobj.tabDDMenuData_MSView;
        var defViewData = this.config.defViewList;
        for (var i in defViewData) {
            if (defViewData.hasOwnProperty(i)) {
                this.viewData.push({
                    txt: defViewData[i].txt,
                    val: defViewData[i].vid,
                    o: 'select',
                    subMenu: [{
                        txt: qslan["vmsub_sel"],
                        selectable: true,
                        val: defViewData[i].vid,
                        o: 'select'
                    }]
                });
            }
        }
        
        this.$showV = this.el.find('.rtq-wl-sp-vl .rtq-ddl-ipt');

        this.updateCurrentView(this.config.currentViewName, '');
        this._createGroupDDL();
        this._createTypeDDL();
        this.createViewMenu(); // create the view list menu
        
        this.chkShowSummary = new Util.ButtonGroup(this.el.find('.summary-show-or-hide'), [{
            txt: qslan["summarylabel"],
            val: 'show'
        }], {
            onClick: function(v, btn){
                self.callbacks.onShowSummaryClick(btn.isSelected);
            }
        }, {
            type: 'checkbox'
        });
        if (self.config.isShowSummary) {
            this.chkShowSummary.btns['show'].select();
        }
        this.eventHandler();
    },
    eventHandler: function(){
        var self = this;
        var timeoutObj;
        var delay = 200;
        //this.el.find('.l4').unbind('mouseover').unbind('mouseout');
        this.el.find('.open-start-up').unbind("click").click(function(){
            self.callbacks.onClickStartUp();
        });
        this.viewEl = this.el.find('.l4 .rtq-wl-sp-vl');
        this.viewEl.unbind('mouseover').bind('mouseover', function(e){
            if (!self._vwDisabled && $(e.target).hasClass("rtq-wl-sp-vl")) {
                clearTimeout(timeoutObj);
                timeoutObj = setTimeout(function(){
                    QS_CustomViewManagement.getCustomviewList(function(o){
                        self.reBindViewMenu(o);
                        self.vwMenu.show();
                    });
                }, delay);
            }
        }).unbind('mouseout').bind('mouseout', function(e){
            if (!Util.contains(self.viewEl[0],e.relatedTarget)) {
                if (!self._vwDisabled) {
                    timeoutObj = setTimeout(function(){
                        self.vwMenu.hide();
                    }, delay);
                }
            }
        });
        this.el.find(".l5").unbind('click').bind("click", function(){// import watchlist from office watchlist
            self.callbacks.onImportClick('office');
        });
        this.el.find(".l6").unbind('click').bind("click", function(){ // import watchlists from Direct 
            self.callbacks.onImportClick('direct');
        });
    },
    _createTypeDDL: function(){
        var self = this;
        this.typeDDL = new Util.DropDownList(this.el.find('.rtq-wl-sp-tl')[0], function(t, v){
            switch (v) {
                case 'list':
                case 'listwrap':
                case 'heatmap':
                    if (self.groupDDL) {
                        self.groupDDL.setDisable(true);
                        self.groupDDL.setTextValue(null, 'la03z');
                    }
                    break;
                case 'listgroup':
                case 'listgroupwrap':
                    if (self.groupDDL) {
                        self.groupDDL.setDisable(false);
                        self.groupDDL.setTextValue(null, 'la03z');
                    }
                    group = 'la03z';
                    break;
            }
            if(v=="heatmap"){
                self.disableView();
            }else{
                self.enableView();
            }
            self.config.displayLayout = v;
            self.callbacks.onChangeDisplayDDL(v);
        }, self.config.layoutList, {
            triggerByClick: false,
            width: 163,
            disable: false,
            actionAtInit: false,
            className: 'rtq-ddl-black'
        });
        self.setTypeDDL(self.config.displayLayout);
    },
    setTypeDDL:function(displayLayout){
        this.config.displayLayout = displayLayout;
        this.typeDDL.setTextValue(null, displayLayout);
    },
    _createGroupDDL: function(){
        var self = this;
        this.groupDDL = new Util.DropDownList(this.el.find('.rtq-wl-sp-gl')[0], function(t, v){
            self.config.groupBy = v;
            self.callbacks.onChangeGroupDDL(v);
        }, self.config.groupByList, {
            triggerByClick: false,
            width: 163,
            disable: false,
            actionAtInit: false,
            className: 'rtq-ddl-black'
        });
        self.setGroupDDL(self.config.groupBy);
        if (!self.config.groupBy || self.config.displayLayout.indexOf('group') == -1) {
            self.disableGroupDDL(true);
        }
    },
    disableGroupDDL: function(isDisable){
        if (this.groupDDL) {
            this.groupDDL.setDisable(isDisable);
        }
    },
    setGroupDDL:function(groupBy){
        this.config.groupBy = groupBy;
        this.groupDDL.setTextValue(null, groupBy);
    },
    //refresh the groupby dropdownlist for LPL
    refreshGroupDDL: function(sourceType, groupBy){
		var qslan=QS_Lang.watchlist;
        if (sourceType == 'LPLP') {
            this.groupDDL.rebindData(this.config.groupByList.concat([{
                txt: qslan["household"],
                val: 'Household'
            }, {
                txt: qslan["accountname"],
                val: 'AccountName'
            }]));
        }
        else 
            if (sourceType == 'LPLH') {
                this.groupDDL.rebindData(this.config.groupByList.concat([{
                    txt: qslan["accountname"],
                    val: 'AccountName'
                }]));
                
            }
            else {
                this.groupDDL.rebindData(this.config.groupByList);
            }
        //var groupBy = this.wtobj.profile.groupBy == 'Household' || this.wtobj.profile.groupBy == 'AccountName' ? 'la03z' : this.wtobj.profile.groupBy;
        this.setGroupDDL(groupBy);
    },
    createViewMenu: function(o){
        var self = this;
        this.vwMenu = new Util.CascadeMenu(self.el.find(".rtq-wl-sp-vl").eq(0), {
            autoHide: true,
            display: false
        }, null, {
            onClick: function(item){
                self._viewAction(item, self.moreDataView);
            }
        });
        //this.reBindViewMenu(o)
    },
    reBindViewMenu: function(o){
        var vData = [],qslan=QS_Lang.watchlist;
        this.moreDataView = [];
        for (var i = 0; i < o.length; i++) {
            if (i < this.config.viewCount) {
                vData.push({
                    txt: o[i].title,
                    val: o[i].id,
                    o: 'select',
                    subMenu: [{
                        txt: qslan["vmsub_sel"],
                        val: o[i].id,
                        selectable: true,
                        o: 'select'
                    }, {
                        txt: qslan["vmsub_edit"],
                        val: o[i].id,
                        selectable: true,
                        o: 'edit'
                    }, {
                        txt: qslan["vmsub_del"],
                        val: o[i].id,
						openMore:false,
                        selectable: true,
                        o: 'delete'
                    }]
                });
            }
            this.moreDataView.push({
                text: o[i].title,
                cmd: o[i].id
            });
        }
        vData = this.viewData.concat(vData);
        if (vData.length != 0) {
            vData.push({
                type: "separator"
            }, {
                txt: qslan["vmsub_more"],
                val: -1,
                o: 'more'
            });
        }
        this.vwMenu.reBind(vData);
    },
    _viewAction: function(item, moreData){
        var self = this;
        var _action = function(item){
            var act = item.data.o, val = item.data.val, txt = item.parent ? item.parent.data.txt : item.data.txt
            switch (act) {
                case 'new':
                    self.callbacks.onViewAction(act, val);
                    break;
                case 'select':
                    //self.updateCurrentView(txt, '');
                    self.callbacks.onViewAction(act, val);
                    //self.wtobj.openColsView(val);
                    break;
                case 'edit':
                    if (val < 1) {
                        return;
                    }
                    self.callbacks.onViewAction(act, val);
                    //self.wtobj.editColsViewPN(txt, val);
                    break;
                case 'delete':
                    if (val < 1) {
                        return;
                    }
					var callback=null;
					if(item.data.openMore){
						callback=function(list){
							self._reBindMore(list, _action);
						};
					}
                    Util.confirm(QS_Lang.text["watchlistcvdelconfirm"], function(b){
                        if (!b) {
                            return;
                        }
                        self.callbacks.onViewAction(act, val,callback);
                    })
                    break;
            }
            
        };
        
        if (item.data.o != null && typeof item.data.o != 'undefined') {
            if (item.data.o == 'more') {
                this._reBindMore(moreData, _action);
            }
            else {
                _action(item);
            }
        }
    },
    _reBindMore: function(data, onclick){
		var self=this,qslan=QS_Lang.watchlist,tab={};
        tab[qslan["dg_titleview"]]=data;
        workspaceManager.openOpenFileWin(tab, function(el){
            //self.wtobj.openColsView(el.getAttribute('cmd'));
            self.updateCurrentView(el.innerText || el.textContent, '');
            self.callbacks.onViewAction('select', el.getAttribute('cmd'));
            //enableViewMenu();
        }, [{
            txt:  qslan["vmsub_sel"],
            val: 'select'
        }, {
            txt:  qslan["vmsub_edit"],
            val: 'edit'
        }, {
            txt:  qslan["vmsub_del"],
            val: 'delete'
        }], function(el, val){
            var id = el.getAttribute('cmd');
            var t = el.innerText || el.textContent;
            onclick({
                data: {
                    o: val,
                    val: id,
                    txt: t,
					openMore:true
                }
            });
            //close more
        });
    },
    disableView: function(){//disable view
        this._vwDisabled = true;
        this.$showV.parent().addClass('rtq-ddl-disable');
    },
    enableView: function(){//enable view
        this._vwDisabled = false;
        this.$showV.parent().removeClass('rtq-ddl-disable');
    },
    updateCurrentView: function(txt, val){//update current view
        this.config.currentViewName = txt;
        this.$showV.text(this.config.currentViewName);
    },
    saveConfig: function(){
        return this.settingPanelPluginForWindow.saveConfig();
    }
};
